package com.sky.controller.user;

import com.sky.constant.MessageConstant;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Slf4j
@Api(tags ="地址管理")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    @ApiOperation("新增地址")
    @PostMapping
    public Result addAddress(@RequestBody AddressBook addressBook){
        log.info("新增地址信息:{}",addressBook);
        addressBookService.insert(addressBook);
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("查询全部地址")
    public Result<List<AddressBook>> getAddress(){
        log.info("查询所有地址");
       List<AddressBook> addressBookList=addressBookService.getAddress();
        return Result.success(addressBookList);
    }
    @GetMapping("/default")
    @ApiOperation("查询默认地址")
    public Result selectDefault(){
        log.info("查询默认的地址");
        List<AddressBook> addressBookList=addressBookService.getDefaultAddress();
        log.info("查询到的地址信息:{}",addressBookList);
        if (addressBookList!=null && addressBookList.size()==1){
            return Result.success(addressBookList.get(0));
        }
        return Result.error(MessageConstant.NO_DEFAULT_ADDRESS);
    }

    @PutMapping
    @ApiOperation("修改地址")
    public Result update(@RequestBody AddressBook addressBook){
        log.info("修改地址");
        addressBookService.updateAddress(addressBook);
        return Result.success();
    }
    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址-数据回显")
    public Result<AddressBook> selectById(@PathVariable Long id){
        log.info("根据id查询地址");
        AddressBook addressBook=addressBookService.selectById(id);
        return Result.success(addressBook);
    }

    @DeleteMapping
    @ApiOperation("根据id删除地址")
    public Result delete( Long id){
        log.info("删除地址,编号:{}",id);
        addressBookService.deleteById(id);
        return Result.success();
    }

    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result setDefaultAddress(@RequestBody AddressBook addressBook){
        log.info("设置默认地址");
        addressBookService.setDefaultAddress(addressBook);
        return Result.success();
    }
}
